package com.leonzhangxf.guice.bill;

import com.leonzhangxf.guice.bill.domain.ChargeResult;
import com.leonzhangxf.guice.bill.domain.CreditCard;
import com.leonzhangxf.guice.bill.domain.Order;
import com.leonzhangxf.guice.bill.domain.Receipt;
import com.leonzhangxf.guice.interceptor.BillIntercept;

import javax.inject.Inject;

/**
 * bill service
 *
 * @author leonzhangxf
 */
public class BillingServiceImpl implements BillingService {

    private final CreditCardProcessor processor;

    private final TransactionLog transactionLog;

    @Inject
    public BillingServiceImpl(CreditCardProcessor processor, TransactionLog transactionLog) {
        this.processor = processor;
        this.transactionLog = transactionLog;
    }

    @BillIntercept
    @Override
    public Receipt chargeOrder(Order order, CreditCard creditCard) {
        try {
            ChargeResult result = processor.charge(creditCard, order.getAmount());
            transactionLog.logChargeResult(result);

            return result.wasSuccessful()
                ? Receipt.forSuccessfulCharge(order.getAmount())
                : Receipt.forDeclinedCharge(result.getDeclineMessage());
        } catch (UnreachableException e) {
            transactionLog.logConnectException(e);
            return Receipt.forSystemFailure(e.getMessage());
        }
    }
}
